import 'package:flutter/material.dart';
import 'package:get/get.dart';

/// 商品规格选择弹窗控制器
class ProductSpecModalController extends GetxController {
  // 商品基本信息
  String productName = '';
  String productImage = '';
  String productPrice = '';

  // 弹窗类型：'cart' 加入购物车, 'buy' 立即购买
  String modalType = 'cart';

  // 选中的规格
  final RxMap<String, String> selectedSpecs = <String, String>{}.obs;

  // 商品数量
  final RxInt quantity = 1.obs;

  // 规格数据
  final RxList<ProductSpecGroup> specGroups = <ProductSpecGroup>[].obs;

  // 数量输入控制器
  final TextEditingController quantityController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    quantityController.text = quantity.value.toString();
    quantityController.addListener(_onQuantityChanged);
  }

  @override
  void onClose() {
    quantityController.dispose();
    super.onClose();
  }

  /// 初始化弹窗数据
  void initModal({
    required String name,
    required String image,
    required String price,
    required String type,
    required List<ProductSpecGroup> specs,
  }) {
    productName = name;
    productImage = image;
    productPrice = price;
    modalType = type;
    specGroups.value = specs;

    // 默认选中第一个规格
    for (var group in specs) {
      if (group.options.isNotEmpty) {
        selectedSpecs[group.name] = group.options.first.name;
      }
    }

    quantity.value = 1;
    quantityController.text = '1';
  }

  /// 选择规格
  void selectSpec(String groupName, String specName) {
    selectedSpecs[groupName] = specName;
  }

  /// 增加数量
  void increaseQuantity() {
    quantity.value++;
    quantityController.text = quantity.value.toString();
  }

  /// 减少数量
  void decreaseQuantity() {
    if (quantity.value > 1) {
      quantity.value--;
      quantityController.text = quantity.value.toString();
    }
  }

  /// 数量输入变化
  void _onQuantityChanged() {
    final text = quantityController.text;
    if (text.isNotEmpty) {
      final value = int.tryParse(text);
      if (value != null && value >= 1) {
        quantity.value = value;
      }
    }
  }

  /// 手动设置数量
  void setQuantity(int value) {
    if (value >= 1) {
      quantity.value = value;
      quantityController.text = value.toString();
    }
  }

  /// 确认操作
  void confirmAction() {
    if (modalType == 'cart') {
      _addToCart();
    } else {
      _buyNow();
    }
  }

  /// 加入购物车
  void _addToCart() {
    // TODO: 实现加入购物车逻辑
    Get.snackbar('提示', '商品已加入购物车');
    Get.back();
  }

  /// 立即购买
  void _buyNow() {
    // TODO: 实现立即购买逻辑
    Get.snackbar('提示', '跳转到订单确认页面');
    Get.back();
  }

  /// 关闭弹窗
  void closeModal() {
    Get.back();
  }
}

/// 商品规格组
class ProductSpecGroup {
  final String name;
  final List<ProductSpecOption> options;

  ProductSpecGroup({required this.name, required this.options});
}

/// 商品规格选项
class ProductSpecOption {
  final String name;
  final String value;
  final bool isAvailable;

  ProductSpecOption({
    required this.name,
    required this.value,
    this.isAvailable = true,
  });
}
